<template>
  <div class="roles-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom:20px">
      <el-breadcrumb-item :to="{ path: 'welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!------------------- 卡片框 -------------------------------->
    <el-card class="box-card">
      <div style="margin-bottom:20px">
        <el-button type="primary" @click="addRoles()">添加角色</el-button>
      </div>
      <!----------------------------- table表格 ------------------------------------------->
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column type="expand">
          <!-- slot-scope="scope" -->
          <template slot-scope="scope">
            <!--------------------- 一级 --------------------------->
            <!-------- 左半边 --------->
            <el-row
              v-for="(item1,index1) in scope.row.children"
              :key="index1"
              align="middle"
              type="flex"
            >
              <el-col :span="8">
                <div class="grid-content bg-purple-dark">
                  <el-tag closable type="success">{{item1.authName}}</el-tag>
                  <span class="el-icon-caret-right"></span>
                </div>
              </el-col>
              <!--------- 右半边  --------->
              <el-col :span="16">
                <div class="grid-content bg-purple-dark">
                  <!-------------------- 二级左 ---------------------------->
                  <el-row
                    v-for="(item2,index2) in item1.children"
                    :key="index2"
                    align="middle"
                    type="flex"
                  >
                    <el-col :span="8">
                      <div class="grid-content bg-purple-dark">
                        <el-tag closable type="warning">{{item2.authName}}</el-tag>
                        <span class="el-icon-caret-right"></span>
                      </div>
                    </el-col>
                    <!------------------------ 二级右 ----------------------------->
                    <el-col :span="16">
                      <div class="grid-content bg-purple-dark">
                        <el-tag
                          closable
                          type="danger"
                          v-for="(item3,index3) in item2.children"
                          :key="index3"
                        >{{item3.authName}}</el-tag>
                      </div>
                    </el-col>
                  </el-row>
                </div>
              </el-col>
            </el-row>
          </template>
          <!------------------- 以上都是插槽 -------------------------->
        </el-table-column>
        <el-table-column type="index" width="50" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <!-- 这里用插槽实现按钮功能 -->
          <template slot-scope="scope">
            <!-- <pre>{{scoped.row}}</pre> -->
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              @click="editRoles(scope.row)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-share"
              size="mini"
              @click="delRoles(scope.row.id)"
            >删除</el-button>
            <el-button
              type="primary"
              icon="el-icon-setting"
              size="mini"
              @click="showRigthsDialog(scope.row)"
            >分配权限</el-button>
            <!-- {{scope.row}} -->
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--======================= 点击分配按钮弹出框 ==========================-->
    <el-dialog title="分配权限" :visible.sync="dialogTableVisible">
      <el-tree
        :data="rightsData"
        show-checkbox
        node-key="id"
        :default-checked-keys="defKeys"
        :props="defaultProps"
        :default-expand-all="true"
        ref="treeList"
      ></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeUsersRights()">确 定</el-button>
      </div>
    </el-dialog>
    <!--====================== 点击编辑按钮弹出窗 ===========================-->
    <el-dialog title="编辑角色" :visible.sync="editDialogFormVisible">
      <el-form :model="editForm" :rules="ruleseditForm" ref="editFormDialog">
        <el-form-item label="角色名称" prop="roleName" :label-width="formLabelWidth">
          <el-input v-model="editForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" :label-width="formLabelWidth">
          <el-input v-model="editForm.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="overEditRoles()">确 定</el-button>
      </div>
    </el-dialog>
    <!--====================== 点击添加角色弹窗 ==============================-->
    <el-dialog title="添加角色" :visible.sync="addDialogFormVisible">
      <el-form :model="addForm" :rules="rulesAddForm" ref="addFormDialog">
        <el-form-item label="角色名称" prop="roleName" :label-width="formLabelWidth">
          <el-input v-model="addForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色区域" prop="roleDesc" :label-width="formLabelWidth">
          <el-input autocomplete="off" v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="setAddRoles()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
           
<script>
import {
  rolesList_api,
  rigthsList_api,
  changeRolesRights_api,
  editRoles_api,
  delRoles_api,
  addRoles_api
} from "@/api/login_api.js";
export default {
  data() {
    return {
      tableData: [],
      //设置分配按钮弹窗
      dialogTableVisible: false,
      //tree组件数组
      rightsData: [],
      //tree组件绑定属性
      defaultProps: {
        children: "children",
        label: "authName"
      },
      //默认勾选的节点的 key 的数组
      defKeys: [],
      roleParams: {
        roleId: "",
        rids: ""
      },
      //编辑角色--------------------------
      editForm: {},
      editDialogFormVisible: false,
      formLabelWidth: "100px",
      //编辑表单校验-------------
      ruleseditForm: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" }
        ]
      },
      //添加角色--------------------
      addDialogFormVisible: false,
      addForm: { roleName: "", roleDesc: "" },
      rulesAddForm: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" }
        ]
      }
    };
  },
  // 渲染页面
  created() {
    this.getRolesList();
  },
  methods: {
    //111获取角色列表------------------------------------------
    async getRolesList() {
      const { data: res } = await rolesList_api();
      // console.log(res,11111);
      this.tableData = res.data;
    },
    //222点击分配按钮打开弹窗-----------------------------------------
    async showRigthsDialog(row) {
      //获取roleId
      this.roleParams.roleId = row.id;
      //  每次点击tree弹框，都先清空数组
      this.defKeys = [];
      //发送axios请求
      const { data: res } = await rigthsList_api("tree");
      // console.log(res,1111111);
      this.rightsData = res.data;
      // console.log(this.rightsData,222222);
      this.digui(row, this.defKeys);
      //最后打开对话框，避免没加载完
      this.dialogTableVisible = true;
    },
    //333通过递归来获取tree列表最里层的id值---------------------------
    digui(row, arr) {
      //如果row里面没有childeren，就不往里面找了，就直接获取row.id
      if (!row.children) return arr.push(row.id);
      // console.log(row.id, 33333);
      //如果有children就遍历 继续找
      row.children.forEach(item => {
        this.digui(item, arr);
      });
    },
    //444在tree弹窗里，更改角色权限-------------------------
    async changeUsersRights() {
      //声明一个空数组，拿到已勾选的数据，所有半选和全选状态下的id
      const keysArray = [
        ...this.$refs.treeList.getHalfCheckedKeys(),
        ...this.$refs.treeList.getCheckedKeys()
      ];
      // console.log(keysArray, 55555555);
      //把数组转成字符串
      this.roleParams.rids = keysArray.join();
      const { data: res } = await changeRolesRights_api(this.roleParams);
      console.log(res, 6666);
      //更新页面
      this.getRolesList();
      this.dialogTableVisible = false;
    },
    //5555添加角色--------------------------------------
    addRoles() {
      this.addDialogFormVisible = true;
    },
    //点击确认添加角色-------------------------------
    setAddRoles() {
      this.$refs.addFormDialog.validate(async valid => {
        if (valid) {
          const { data: res } = await addRoles_api(this.addForm);
          console.log(res, 77777);
          this.addDialogFormVisible = false;
          this.getRolesList();
        } else {
          this.$message.error("输入错误！");
          return false;
        }
      });
    },
    //6666点击编辑按钮------------------------------
    editRoles(row) {
      this.editDialogFormVisible = true;
      //点击弹窗默认显示数据
      this.editForm = row;
    },
    //7777点击弹窗的确认按钮，完成编辑角色---------
    overEditRoles() {
      this.$refs.editFormDialog.validate(async valid => {
        if (valid) {
          const { data: res } = await editRoles_api(this.addForm);
          console.log(res, 999999);
          this.editDialogFormVisible = false;
        } else {
          this.$message.error("输入错误！");
          return false;
        }
      });
    },
    //点击取消刷新页面-------------
    close() {
      this.getRolesList();
      this.editDialogFormVisible = false;
    },
    //88888点击删除按钮-------------------------
    async delRoles(id) {
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
      // console.log(res,333333); //返回confirm
      if (res == "confirm") {
        const { data: res } = await delRoles_api(id);
        console.log(res, 777777);
        this.getRolesList();
        this.$message({
          type: "success",
          message: "删除成功!"
        });
      }
    }
  }
};
</script>
<style scoped lang="less">
.el-row {
  border-top: 1px solid #ccc;
  // padding: 5px 0;
  &:nth-child(1) {
    border: 0;
  }
  .el-tag {
    margin: 5px;
  }
}
</style>